<?php
namespace app\model;

use think\api\Client;
use think\facade\Log;
use think\facade\Queue;
use think\Model;

class Task extends Model {
	//protected $field = true;

    public static function getAvaTask($device_id,$album_id){

        //设备id
        //$where[] = ['device_ids','find in set',$device_id];
        //分组id
        $type_ids=ViidDeviceRelate::where(['device_id'=>$device_id])->column('type_id');
        if($type_ids){
            $where[]=['type_id','in',$type_ids];
        }
        //指定底库
        if($album_id){
            $where[]=['album_id','find in set',$album_id];
        }
        //标签id
        $label_ids=ViidDevice::where(['id'=>$device_id])->column('label_ids');
        if($label_ids){
            //Log::info("tasks:::".json_encode($label_ids));
            $where[]=['label_id','in',explode(",",$label_ids[0])];
        }
        //$where_status[] = ['status','=',1];
        $where[] = ['status','=',1];
        //$tasks=self::where($where_status)->where(function($query) use ($where){$query->whereOr($where);})->select();
        $tasks=self::where($where)->select();
        Log::info("sql:".self::getLastSql());
        if($tasks){
            $now=date('Y-m-d H:i:s');
            for ($i=0;$i<count($tasks);$i++){
                if($tasks[$i]['status']==1){
                    if($now<$tasks[$i]['start_time']||$now>$tasks[$i]['end_time']){
                        unset($tasks[$i]);
                    }
                }
            }
        }
        Log::info("可用任务：".json_encode($tasks));

        return $tasks;
    }

    public static function finishTask($task,$queue){
        Log::info("cat7queue:".$queue);
        $now = date('Y-m-d H:i:s');
        $sms = config('capture.sms');
        $client = new Client($sms['app_code']);
        TaskLogs::create(['task_id' => $task['id'], 'photo_id' => $task['photo_id'],'create_at'=>$now]);
        //开始判断
        $flag=false;
        $search[]=['create_at','>',date('Y-m-d H:i:s',strtotime('- '.$task['timespan'].' minutes'))];
        $search[]=['task_id','=',$task['id']];
        $job_data = [];
        $job_data["ts"] = time();
        $job_data["bizid"] = uniqid();
        $job_data["params"] =$task;
        if($task['category']==1||$task['category']==3){
            $count=TaskLogs::where($search)->count();
            if($count>$task['personnum']){
                $flag=true;
            }
        }elseif ($task['category']==2){
            $counts=TaskLogs::where($search)->group('photo_id')->count();
            foreach ($counts as $count){
                if($count['count(*)']>$task['personnum']){
                    $flag=true;
                }
            }
        }elseif ($task['category']==4){
            if($queue){
                Queue::later(10,\app\job\Task::class,$job_data,'task_list');
            }else{
                $count=TaskLogs::where($search)->count();
                if($count>$task['personnum']){
                    $flag=true;
                }
            }
        }elseif ($task['category']==5){
            //规定时间内，监护人是否出现
            if($queue){
                Queue::later($task['timespan']*60,\app\job\Task::class,$job_data,'task_list');
            }else{
                //查到监护人照片，然后到face表里面去找对应的人
                $album_photo=AlbumPhoto::where(['photo_id'=>$task['photo_id'],'album_id'=>$task['album_id']])->find();
                if($album_photo){
                    $_face=new Faces();
                    $compare=$_face->compare(base64_img($album_photo['file_path'].$album_photo['id'].'_follow.jpg'));
                    $photo_id=$compare['photo_id'];
                    $last_photo=$_face->where('photo_id',$photo_id)->order('id desc')->find();
                    if(!$last_photo||(time()-strtotime($last_photo['create_time'])>$task['timespan']*60)){
                        $flag=true;
                    }
                }
                $count=TaskLogs::where($search)->count();
                if($count>$task['personnum']){
                    $flag=true;
                }
            }
        }elseif($task['category']==7) {
            Log::info('cat7task:'.json_encode($task));
            //规定时间内，是否出现另外一个相册的人
            if($queue){
                Queue::later($task['timespan']*60,\app\job\Task::class,$job_data,'task_list_7');
            }else{
                $flag=true;
                //查到监护人照片，然后到face表里面去找对应的人
                $_face=new Faces();
                $where=[['device_id','=',$task['find_device_id'],['create_time','<',date("Y-m-d H:i:s",strtotime("-1 minute"))]]];
                $lists=$_face->where($where)->select();
                Log::info('cat7条件：'.json_encode($where));
                Log::info('cat7所有人：'.json_encode($lists));
                if($lists){
                    foreach ($lists as $list) {
                        $res=$_face->compare_by_album_ids(base64_img($list['file_path'].$list['id'].'_bg.jpg'),$task['compare_album_id']);
                        Log::info('cat7比较结果:'.json_encode($res));
                        if($res){
                            $flag=false;
                            break;
                        }
                    }
                }else{
                    $flag=true;
                }

            }
        }elseif ($task['category']==9){
            $flag=true;
        }
        if($flag){
            $alert['task_id'] = $task['id'];
            $alert['task_name']=$task['name'];
            $alert['photo_id'] = $task['push_id'];
            $alert['face_id'] = $task['face_id'];
            //$alert['dongjian_result']=$task['dongjian_result'];
            $alert['create_at'] = $now;
            TaskAlert::create($alert);
            $mobiles=explode(",",$task['mobile']);
            foreach ($mobiles as $mobile){
                $client->smsSend()
                    ->withSignId($sms['sign_id'])
                    ->withTemplateId($sms['template_id'])
                    ->withPhone($mobile)
                    ->request();
            }
            Log::info('发送短信：' . $task['mobile'] . ":::" . $alert['id']);
        }
    }
}